//node 内置得promise化函数
const { promisify } = require('util')
const path = require('path')
const { vueRepo } = require('../config/repo-config')
const { commandSpawn } = require('../utils/terminal')

/* 

  1. clone 项目

  2. 执行npm install

  3. 运行npm run serve

  4. 打开浏览器

*/

//从git中下载代码的插件
// https://www.npmjs.com/package/download-git-repo
const download = promisify(require('download-git-repo'))

const fs = require('fs').promises
//创建一个项目
const createProjectAction = async (project) => {
  try {
    //1. 下载文件到本地,第二个参数默认是从进程路径开始
    console.log('开始下载...')
    await download(vueRepo, project, { clone: true })
    console.log('下载完成')

    // 2. 执行npm install
    // windows下不是执行的npm 而是 npm.cmd
    // 获取操作系统 并 设置命令,由于我这里下载了cnpm,那么直接用cnpm吧
    const command = process.platform == 'win32' ? 'cnpm.cmd' : 'npm'
    // await commandSpawn('cnpm.cmd', ['install'], { cwd: `./${project}` })
    await commandSpawn(command, ['install'], { cwd: `./${project}` })

    // 3. 执行npm run serve
    await commandSpawn(command, ['run','serve'], { cwd: `./${project}` })

    // 4. 打开浏览器
    // 需要插件 open
    // open('dizhi')
  } catch (error) {
    console.log('执行错误')
    console.error(error)
  }
}

module.exports = { createProjectAction }
